# -*- coding: utf-8 -*-
# @Date   : 2021/5/11
# @File   : R19_EG_CASE_FinancialLitigationSixMonsCheck_WHB.py
# @Author : zhangxuchuo

'''eof
name:近半年新增金融类诉讼（开庭公告、裁判文书）
code:R19_EG_CASE_FinancialLitigationSixMonsCheck_WHB
tableName:
columnName:
groups:弱规则>司法信息校验
dependencies:EG_CASE_DSJ
type:常用指标
datasourceType:在线指标
description:
eof'''

import sys
import pandas as pd
import json
from datetime import datetime
reload(sys)
sys.setdefaultencoding('utf-8')

def FormatData(tableName):
    try:
        eg = EG_CASE_DSJ.get("data").get(tableName)
        return eg if isinstance(eg, list) else [{}]
    except:
        return [{}]


def formatDate(time):
    try:
        import re
        import datetime
        r1 = re.compile(u'年|月|日')
        time = r1.sub('.', time)
        try:
            date = datetime.datetime.strptime(time, '%Y.%m.%d').strftime('%Y%m%d')
        except:
            try:
                date = datetime.datetime.strptime(time, '%Y-%m-%d').strftime('%Y%m%d')
            except:
                try:
                    date = datetime.datetime.strptime(time, '%Y/%m/%d').strftime('%Y%m%d')
                except:
                    try:
                        r = re.compile(r'\D+')
                        tmp = r.sub('', time)
                        if len(tmp) > 8:
                            tmp = tmp[:8]
                        date = datetime.datetime.strptime(tmp, '%Y%m%d').strftime('%Y%m%d')
                    except:
                        date = None
        return date
    except:
        return None


def get_date_list():
    try:
        now = datetime.now()
        aaa = [(now + pd.tseries.offsets.DateOffset(months=i)).strftime('%Y%m%d') for i in [-6, 0]]
        return aaa
    except:
        return None


def float_num(str):
    try:
        return float(str)
    except:
        return None


def typeMatch(type):
    if type in null_type_list:
        return False
    typeList = [u"银行", u"分行", u"支行", u"小额贷款", u"信用卡", u"贷记卡", u"买卖", u"担保", u"付款", u"借款", u"利息", u"结算", u"债权", u"借贷"]
    for i in typeList:
        if i in type:
            return True
    return False


null_type_list = ['', ' ', None, 'null', 'Null', 'NULL', '/', '-', '--']


# def getRule54():
#     ktggList = FormatData("R227")
#     date_list = get_date_list()
#     if ktggList == [{}]:
#         return u'缺失值'
#     else:
#         if len(ktggList) >= 1:
#             resultList = []
#             for i in ktggList:
#                 PTYPE = i.get("PTYPE")
#                 CASEDATE = i.get("CASEDATE")
#                 if CASEDATE in null_type_list or len(CASEDATE) < 10:
#                     resultList.append(2)
#                 CASEDATE = formatDate(CASEDATE[0:10])
#                 CASEREASON = i.get("CASEREASON")
#                 TARGET = i.get("TARGET")
#                 if PTYPE not in null_type_list and (PTYPE == "15" or PTYPE == "16") and CASEDATE not in null_type_list \
#                         and CASEREASON not in null_type_list and TARGET not in null_type_list:
#                     if (typeMatch(CASEREASON) or typeMatch(TARGET)) and date_list[0] < CASEDATE < date_list[1]:
#                         resultList.append(0)
#                     else:
#                         resultList.append(1)
#                 else:
#                     resultList.append(1)
#             if len(resultList) > 0:
#                 if min(resultList) == 0:
#                     return 0
#                 elif max(resultList) == 2:
#                     return 2
#                 else:
#                     return 1
#             else:
#                 return 1
#         else:
#             return 1

def getRule54():
    ktggList_1 = FormatData("R227")
    ktggList_2 = FormatData("FR227")
    date_list = get_date_list()
    resultList = []
    if ktggList_1 == [{}] and ktggList_2 == [{}]:
        return  u'缺失值'
    if ktggList_1 == [{}]:
        pass
    else:
        if len(ktggList_1) >= 1:
            for i in ktggList_1:
                PTYPE = i.get("PTYPE")
                CASEDATE = i.get("CASEDATE")
                if CASEDATE in null_type_list or len(CASEDATE) < 10:
                    resultList.append(2)
                    continue
                CASEDATE = formatDate(CASEDATE[0:10])
                CASEREASON = i.get("CASEREASON")
                TARGET = i.get("TARGET")
                if PTYPE not in null_type_list and (PTYPE == "15" or PTYPE == "16") and CASEDATE not in null_type_list \
                        and CASEREASON not in null_type_list and TARGET not in null_type_list:
                    if (typeMatch(CASEREASON) or typeMatch(TARGET)) and date_list[0] < CASEDATE < date_list[1]:
                        resultList.append(0)
                    else:
                        resultList.append(1)
                else:
                    resultList.append(1)
        else:
            resultList.append(1)

    if ktggList_2 == [{}]:
        pass
    else:
        if len(ktggList_2) >= 1:
            for i in ktggList_2:
                PTYPE = i.get("PTYPE")
                CASEDATE = i.get("CASEDATE")
                if CASEDATE in null_type_list or len(CASEDATE) < 10:
                    resultList.append(2)
                    continue
                CASEDATE = formatDate(CASEDATE[0:10])
                CASEREASON = i.get("CASEREASON")
                TARGET = i.get("TARGET")
                if PTYPE not in null_type_list and (PTYPE == "15" or PTYPE == "16") and CASEDATE not in null_type_list \
                        and CASEREASON not in null_type_list and TARGET not in null_type_list:
                    if (typeMatch(CASEREASON) or typeMatch(TARGET)) and date_list[0] < CASEDATE < date_list[1]:
                        resultList.append(0)
                    else:
                        resultList.append(1)
                else:
                    resultList.append(1)
        else:
            resultList.append(1)
    if len(resultList) > 0:
        if min(resultList) == 0:
            return 0
        elif max(resultList) == 2:
            return 2
        else:
            return 1
    else:
        return 1


# if __name__ == "__main__":
#     file_obj = open(r'C:\Users\john\Desktop\samples\EG_CASE_DSJ.json', 'r')
#     content = file_obj.read()
#     EG_CASE_DSJ = eval(content)['EG_CASE_DSJ']
# # EG_CASE_DSJ = json.loads(content, strict=False)
#     aa = getRule54()
#     print aa

result = getRule54()
